﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ShoppingWebPage.Models
{
    public class Cart
    {
        public int id { get; set; }
        public int Quantity { get; set; }
        public string cartName { get; set; }
        public double totalBalance { get; set; }
        public int totalItems { get; set; }
        public List<Item> Items { get; set; }
        public Cart()
        {
            this.cartName = "Cart";
            this.totalBalance = 0;
            Items = new List<Item>();
        }
        public void AddToCart(Item item)
        {
            var cart = HttpContext.Current.Session[this.cartName] as Cart;
            if (cart == null)
            {
                cart = new Cart();
                HttpContext.Current.Session[this.cartName] = cart;
            }
            cart.AddItem(cart, item);
            HttpContext.Current.Session[this.cartName] = cart;
        }
        public void SaveCart(Cart cart)
        {
            HttpContext.Current.Session[this.cartName] = cart;
        }
        public void AddItem(Cart cart, Item item)
        {
            foreach (var sessionItem in cart.Items)
            {
                if (sessionItem.id == item.id)
                {
                    ++sessionItem.quantity;
                    sessionItem.itemTotalPrice = sessionItem.quantity * sessionItem.price;
                    return;
                }
            }
            item.itemTotalPrice = item.price * item.quantity;
            cart.Items.Add(item);
        }
        public void UpdateItems(Cart cart, Item item)
        {
            if (item.quantity != 0)
            {
                item.itemTotalPrice = item.price * item.quantity;
                cart.Items.Add(item);
            }
        }
        public Cart NewCart(string id)
        {
            var cart = HttpContext.Current.Session[id] as Cart;
            if (cart == null)
            {
                cart = new Cart();
                HttpContext.Current.Session[id] = cart;
            }
            return cart;
        }
        
    }
}